package jstart.exe;

import java.io.File;
import java.util.Properties;
import javax.swing.*;

/**
 * @author zw-zheng
 * Created on 2021-02-09
 */
public class DefaultLauncher implements Launcher {

    private static final String PROPERTIES_FILE = "jstart.properties";
    private static String[] sSystemProps;
    final LaunchContext context;
    private final Properties config;
    private JFrame frame;
    private JTextArea jtaInfo;

    public DefaultLauncher(LaunchContext context) {
        this.context = context;
        Properties defaultConfig = new Properties();
        Kits.loadProps(defaultConfig,
                       context.getClassLoader()
                              .getResourceAsStream(PROPERTIES_FILE));
        this.config = new Properties(defaultConfig);
    }

    @Override public void launch() throws Exception {
        initInfo();
        frame.setVisible(true);
    }

    String getProperty(String name, String defaultValue) {
        if (config.isEmpty()) {
            Kits.loadProps(config, new File(context.getBootDir(), PROPERTIES_FILE));
        }
        return config.getProperty(name, defaultValue);
    }

    private void initInfo() {
        frame = new JFrame(context.getBootDir()
                                  .getAbsolutePath());
        frame.setSize(480, 270);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        jtaInfo = new JTextArea();
        jtaInfo.setEditable(false);
        frame.add(jtaInfo);

        if (sSystemProps == null) {
            sSystemProps = new String[] {
                    // java props
                    "java.home",
                    "java.version",
                    "java.class.version",
                    "java.class.path",
                    "java.library.path",
                    "java.io.tmpdir",
                    // os props
                    "os.name",
                    "os.version",
                    "os.arch",
                    // user props
                    "user.dir",
                    "user.home",
                    "user.country",
                    // encoding
                    "file.encoding",
            };
        }

        jtaInfo.append("使用方法：\n");
        jtaInfo.append("java -jar jstart.jar [option]\n");
        jtaInfo.append("option: \n");
        jtaInfo.append("    -l, --launch  启动应用程序\n");
        jtaInfo.append("    -u, --update  更新应用程序\n");
        jtaInfo.append("环境变量和系统属性：\n");
        jtaInfo.append("app.home=" + System.getenv("app.home"));
        jtaInfo.append("\n");
        for (String name : sSystemProps) {
            jtaInfo.append(name);
            jtaInfo.append("=");
            jtaInfo.append(System.getProperty(name));
            jtaInfo.append("\n");
        }
        jtaInfo.append("config.size=" + config.size());
    }
}
